package com.coolgor.axnut.web.mdmis;

import org.springframework.stereotype.Controller;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.coolgor.axnut.util.AddressResolutionUtil;
import com.coolgor.axnut.util.HttpServletRequestUtil;
import com.coolgor.axnut.dto.mdmis.DeliverInfoExecution;
import com.coolgor.axnut.dto.mdmis.MDMISOperationTraceExecution;
import com.coolgor.axnut.dto.mdmis.PolicyExecution;
import com.coolgor.axnut.entity.auth.LocalUser;
import com.coolgor.axnut.entity.auth.Role;
import com.coolgor.axnut.entity.mdmis.DeliverInfo;
import com.coolgor.axnut.entity.mdmis.MDMISOperationTrace;
import com.coolgor.axnut.entity.mdmis.Policy;
import com.coolgor.axnut.entity.mdmis.PolicyCondition;
import com.coolgor.axnut.entity.mdmis.PolicyMonitor;
import com.coolgor.axnut.enums.mdmis.PolicyStatusEnum;
import com.coolgor.axnut.exceptions.mdmis.PolicyOperationException;
import com.coolgor.axnut.enums.mdmis.PolicyMonitorEnum;
import com.coolgor.axnut.enums.mdmis.PolicyOperationStateEnum;
import com.coolgor.axnut.service.mdmis.DeliverInfoService;
import com.coolgor.axnut.service.mdmis.MDMISOperationTraceService;
import com.coolgor.axnut.service.mdmis.PolicyMonitorService;
import com.coolgor.axnut.service.mdmis.PolicyService;


@Controller
@RequestMapping(value="mdmis", method={RequestMethod.GET,RequestMethod.POST})
public class PolicyController {
	@Autowired
	private  PolicyService policyService;
	@Autowired
	private  PolicyMonitorService policyMonitorService;
	@Autowired
	private  DeliverInfoService deliverInfoService;
	@Autowired
	private MDMISOperationTraceService operationTraceService;
	
	@RequestMapping(value = "/importPolicy", method={RequestMethod.GET,RequestMethod.POST})
	@ResponseBody
	private Map<String, Object> importPolicy(HttpServletRequest request) {
		Map<String, Object> modelMap = new HashMap<String, Object>();
		String insureNoString = HttpServletRequestUtil.getString(request, "insureNos");
		List<Policy> importSuccessList = new ArrayList<Policy>();
		Policy policy ;
		Policy policyTemp ;	
		PolicyExecution flag;
	    if (!"".equals(insureNoString) && insureNoString!=null) {
	    	String[] insureNos = insureNoString.split(",");
	    	//循环操作每一张保单
	    	for (int i=0; i<insureNos.length; i++) {
	    		policyTemp = policyService.getTempPolicy(insureNos[i]);
	    		policy = policyTemp;
	    		policy.setArea(AddressResolutionUtil.getGXArea(policyTemp.getAddress()));
	    		policy.setStatus(Integer.valueOf(PolicyStatusEnum.INTRO.getState()));
	    		policy.setStatusInfo(PolicyStatusEnum.INTRO.getStateInfo());
	    		flag = null;
	    		try {
	    			flag = policyService.addPolicy(policy);
	    			if (flag.getState()==PolicyOperationStateEnum.SUCCESS.getState()) {
			    		importSuccessList.add(policyTemp);
		    		} else {
		    			policyTemp.setRemark(policyTemp.getRemark()+"[SystemErrorInformation]未知原因导入失败！");
		    			policyService.modifyTempPolicy(policyTemp);
		    		}
	    		} catch (Exception e) {
	    			System.err.println(e);
	    			policyTemp.setRemark(policyTemp.getRemark()+"[SystemErrorInformation]存在相同的投保单号，导入失败！");
	    			policyService.modifyTempPolicy(policyTemp);
	    		}	    		
	    	}
	    	flag = null;
	    	flag = policyService.batchRemoveTempPolicy(importSuccessList);
	    	if (flag.getState()==PolicyOperationStateEnum.SUCCESS.getState()) {
				modelMap.put("success", true);
				modelMap.put("total", importSuccessList.size());
    		} else {
    			modelMap.put("success", false);
    			modelMap.put("errMsg", "clear import pool error!");
    		}
	    	//关键操作，需要记录
	    	if ((boolean) modelMap.get("success")) {
			    this.markOperation(request, "导入保单信息", insureNoString, "操作成功", null);
	    	} else {
			    this.markOperation(request, "导入保单信息", insureNoString, (String)modelMap.get("errMsg"), null);
	    	}
	    } else {
			modelMap.put("success", false);
			modelMap.put("errMsg", "Empty Parameter");
		}
		return modelMap;
	}	
	
	@RequestMapping(value = "/getPolicyImportPool", method={RequestMethod.GET,RequestMethod.POST})
	@ResponseBody
	private Map<String, Object> getPolicyImportPool(HttpServletRequest request) {
		Map<String, Object> modelMap = new HashMap<String, Object>();
	    int page = HttpServletRequestUtil.getInt(request, "page");
	    int pageSize = HttpServletRequestUtil.getInt(request, "rows");
	    Policy policyCondition = new Policy();
	    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
	    String introTime = HttpServletRequestUtil.getString(request, "introTime");
	    if (!"".equals(introTime) && introTime!=null) {
	    	try {
				policyCondition.setIntroTime(sdf.parse(introTime));
			} catch (ParseException e) {
				e.printStackTrace();
			}
	    }
	    String insureTime = HttpServletRequestUtil.getString(request, "insureTime");
	    if (!"".equals(insureTime) && insureTime!=null) {
	    	try {
				policyCondition.setInsureTime(sdf.parse(insureTime));
			} catch (ParseException e) {
				e.printStackTrace();
			}
	    }
	    PolicyExecution exe = policyService.getTempPolicyList(policyCondition, page, pageSize);
		if (null != exe ) {
			try {
				modelMap.put("total",exe.getCount());
				modelMap.put("rows",exe.getList());
				modelMap.put("success", true);
			} catch (Exception e) {
				modelMap.put("success", false);
				modelMap.put("errMsg", e.toString());
			}
		} else {
			modelMap.put("success", false);
			modelMap.put("errMsg", "Empty List");
		}
		return modelMap;
	}
	
	@RequestMapping(value = "/removeTempPolicy", method={RequestMethod.POST})
	@ResponseBody
	private Map<String, Object> removeTempPolicy(HttpServletRequest request) {
		Map<String, Object> modelMap = new HashMap<String, Object>();
		String insureNoString = HttpServletRequestUtil.getString(request, "insureNos");
		List<Policy> list = new ArrayList<Policy>();
		Policy policy ;
	    if (!"".equals(insureNoString) && insureNoString!=null) {
	    	String[] insureNos = insureNoString.split(",");
	    	for (int i=0; i<insureNos.length; i++) {
	    		policy = new Policy();
	    		policy.setInsureNo(insureNos[i]);
	    		list.add(policy);
	    	}
	    	PolicyExecution exe = policyService.batchRemoveTempPolicy(list);
	    	if (null != exe ) {
				try {
					modelMap.put("total",exe.getCount());
					modelMap.put("success", true);
				} catch (Exception e) {
					modelMap.put("success", false);
					modelMap.put("errMsg", e.toString());
				}
			} else {
				modelMap.put("success", false);
				modelMap.put("errMsg", "Empty List");
			}
	    } else {
			modelMap.put("success", false);
			modelMap.put("errMsg", "Empty Parameter");
		}
		return modelMap;
	}	
	
	@RequestMapping(value = "/getPolicyInfo", method={RequestMethod.POST})
	@ResponseBody
	private Map<String, Object> getPolicyInfo(HttpServletRequest request) {
		Map<String, Object> modelMap = new HashMap<String, Object>();
	    Policy policy = null;
	    String insureNo = HttpServletRequestUtil.getString(request, "insure_no");
	    if (!"".equals(insureNo) && insureNo!=null) {
	    	policy = policyService.getPolicy(insureNo);
			if (null != policy ) {
				try {
					modelMap.put("data",policy);
					modelMap.put("success", true);
				} catch (Exception e) {
					modelMap.put("success", false);
					modelMap.put("errMsg", e.toString());
				}
			} else {
				modelMap.put("success", false);
				modelMap.put("errMsg", "Empty insure information!");
			}
	    	//关键操作，需要记录
	    	if ((boolean) modelMap.get("success")) {
			    this.markOperation(request, "查询保单信息", policy.toString(), "操作成功", null);
	    	} else {
			    this.markOperation(request, "查询保单信息", insureNo, (String)modelMap.get("errMsg"), null);
	    	}
	    } else {
	    	modelMap.put("success", false);
			modelMap.put("errMsg", "Empty insure NO");
	    }	    
		return modelMap;
	}	
	
	@RequestMapping(value = "/getPolicyList", method={RequestMethod.POST})
	@ResponseBody
	private Map<String, Object> getPolicyList(HttpServletRequest request) {
		Map<String, Object> modelMap = new HashMap<String, Object>();
	    int page = HttpServletRequestUtil.getInt(request, "page");
	    int pageSize = HttpServletRequestUtil.getInt(request, "rows");
	    Policy policyCondition = new Policy();
	    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
	    String insureNo = HttpServletRequestUtil.getString(request, "insureNo");
	    if (!"".equals(insureNo) && insureNo!=null) {
	    	policyCondition.setInsureNo(insureNo);
	    }
	    String application = HttpServletRequestUtil.getString(request, "application");
	    if (!"".equals(application) && application!=null) {
	    	policyCondition.setApplicant(application);
	    }
	    String mobilephone = HttpServletRequestUtil.getString(request, "mobilephone");
	    if (!"".equals(mobilephone) && mobilephone!=null) {
	    	policyCondition.setMobilephone(mobilephone);
	    }
	    String insureTime = HttpServletRequestUtil.getString(request, "insureTime");
	    if (!"".equals(insureTime) && insureTime!=null) {
	    	try {
				policyCondition.setInsureTime(sdf.parse(insureTime));
			} catch (ParseException e) {
				e.printStackTrace();
			}
	    }
	    PolicyExecution exe = policyService.getPolicyList(policyCondition, page, pageSize);
		if (null != exe ) {
			try {
				modelMap.put("total",exe.getCount());
				modelMap.put("rows",exe.getList());
				modelMap.put("success", true);
			} catch (Exception e) {
				modelMap.put("success", false);
				modelMap.put("errMsg", e.toString());
			}
		} else {
			modelMap.put("success", false);
			modelMap.put("errMsg", "Empty List");
		}
		return modelMap;
	}
	
	@RequestMapping(value = "/getPolicyListByCondition", method={RequestMethod.POST})
	@ResponseBody
	private Map<String, Object> getPolicyListByCondition(HttpServletRequest request) {
		Map<String, Object> modelMap = new HashMap<String, Object>();
	    int page = HttpServletRequestUtil.getInt(request, "page");
	    int pageSize = HttpServletRequestUtil.getInt(request, "rows");
	    PolicyCondition policyCondition = new PolicyCondition();
	    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
	    String insureNo = HttpServletRequestUtil.getString(request, "insureNo");
	    if (!"".equals(insureNo) && insureNo!=null) {
	    	policyCondition.setInsureNo(insureNo);
	    }
	    String application = HttpServletRequestUtil.getString(request, "application");
	    if (!"".equals(application) && application!=null) {
	    	policyCondition.setApplicant(application);
	    }
	    String mobilephone = HttpServletRequestUtil.getString(request, "mobilephone");
	    if (!"".equals(mobilephone) && mobilephone!=null) {
	    	policyCondition.setMobilephone(mobilephone);
	    }
	    Integer status = HttpServletRequestUtil.getInt(request, "status");
	    if ( status!=null && status>0 ) {
	    	policyCondition.setStatus(status);
	    }
	    String project = HttpServletRequestUtil.getString(request, "project");
	    if (!"".equals(project) && project!=null) {
	    	policyCondition.setProject(project);
	    }
	    String policyType = HttpServletRequestUtil.getString(request, "policy_type");
	    if (!"".equals(policyType) && policyType!=null) {
	    	policyCondition.setPolicyType(policyType);
	    }
	    Integer deliverCount1 = HttpServletRequestUtil.getInt(request, "deliverCount1");
	    if ( deliverCount1!=null && deliverCount1>0 ) {
	    	policyCondition.setDeliverCount1(deliverCount1);
	    }
	    Integer deliverCount2 = HttpServletRequestUtil.getInt(request, "deliverCount2");
	    if ( deliverCount2!=null && deliverCount2>0 ) {
	    	policyCondition.setDeliverCount2(deliverCount2);
	    }
	    String address = HttpServletRequestUtil.getString(request, "address");
	    if (!"".equals(address) && address!=null) {
	    	policyCondition.setAddress(address);
	    }
	    //到达广西的时间 introTime
	    String introTimeBegin = HttpServletRequestUtil.getString(request, "introTimeBegin");
	    if (!"".equals(introTimeBegin) && introTimeBegin!=null) {
	    	try {
				policyCondition.setIntroTimeBegin(sdf.parse(introTimeBegin));
			} catch (ParseException e) {
				e.printStackTrace();
			}
	    }
	    String introTimeEnd = HttpServletRequestUtil.getString(request, "introTimeEnd");
	    if (!"".equals(introTimeEnd) && introTimeEnd!=null) {
	    	try {
				policyCondition.setIntroTimeEnd(sdf.parse(introTimeEnd));
			} catch (ParseException e) {
				e.printStackTrace();
			}
	    }
	    //投保日期 insureTime
	    String insureTimeBegin = HttpServletRequestUtil.getString(request, "insureTimeBegin");
	    if (!"".equals(insureTimeBegin) && insureTimeBegin!=null) {
	    	try {
				policyCondition.setInsureTimeBegin(sdf.parse(insureTimeBegin));
			} catch (ParseException e) {
				e.printStackTrace();
			}
	    }
	    String insureTimeEnd = HttpServletRequestUtil.getString(request, "insureTimeEnd");
	    if (!"".equals(insureTimeEnd) && insureTimeEnd!=null) {
	    	try {
				policyCondition.setInsureTimeEnd(sdf.parse(insureTimeEnd));
			} catch (ParseException e) {
				e.printStackTrace();
			}
	    }
	    //回销日期 receiptTime
	    String receiptTimeBegin = HttpServletRequestUtil.getString(request, "receiptTimeBegin");
	    if (!"".equals(receiptTimeBegin) && receiptTimeBegin!=null) {
	    	try {
				policyCondition.setReceiptTimeBegin(sdf.parse(receiptTimeBegin));
			} catch (ParseException e) {
				e.printStackTrace();
			}
	    }
	    String receiptTimeEnd = HttpServletRequestUtil.getString(request, "receiptTimeEnd");
	    if (!"".equals(receiptTimeEnd) && receiptTimeEnd!=null) {
	    	try {
				policyCondition.setReceiptTimeEnd(sdf.parse(receiptTimeEnd));
			} catch (ParseException e) {
				e.printStackTrace();
			}
	    }
	    //原单退回的日期 returnTime
	    String returnTimeBegin = HttpServletRequestUtil.getString(request, "returnTimeBegin");
	    if (!"".equals(returnTimeBegin) && returnTimeBegin!=null) {
	    	try {
				policyCondition.setReturnTimeBegin(sdf.parse(returnTimeBegin));
			} catch (ParseException e) {
				e.printStackTrace();
			}
	    }
	    String returnTimeEnd = HttpServletRequestUtil.getString(request, "returnTimeEnd");
	    if (!"".equals(returnTimeEnd) && returnTimeEnd!=null) {
	    	try {
				policyCondition.setReturnTimeEnd(sdf.parse(returnTimeEnd));
			} catch (ParseException e) {
				e.printStackTrace();
			}
	    }
	    PolicyExecution exe = policyService.getPolicyList(policyCondition, page, pageSize);
		if (null != exe ) {
			try {
				modelMap.put("total",exe.getCount());
				modelMap.put("rows",exe.getList());
				modelMap.put("success", true);
			} catch (Exception e) {
				modelMap.put("success", false);
				modelMap.put("errMsg", e.toString());
			}
		} else {
			modelMap.put("success", false);
			modelMap.put("errMsg", "Empty List");
		}
		return modelMap;
	}
	
	@RequestMapping(value = "/addPolicy", method={RequestMethod.POST})
	@ResponseBody
	private Map<String, Object> addPolicy(@RequestBody Policy policy, HttpServletRequest request) {
		Map<String, Object> modelMap = new HashMap<String, Object>();
		if (null == policy) {
			modelMap.put("success", false);
			modelMap.put("errMsg", "Empty Policy Entity!");
			return modelMap;
		}
		// 更新保单的状态信息
		policy.setStatusInfo(PolicyStatusEnum.stateOf(policy.getStatus()).getStateInfo());
		PolicyExecution exe = null ; 
	    try {
			exe = policyService.addPolicy(policy);
	    } catch (Exception e) {
	    	modelMap.put("success", false);
			modelMap.put("errMsg", "出现异常，执行出错！\n请检查投保单号是否已经存在。");
			return modelMap;
		}		
	    // 
		if (null != exe ) {
			try {
				modelMap.put("total",exe.getCount());
				modelMap.put("rows",exe.getList());
				modelMap.put("success", true);
			} catch (Exception e) {
				modelMap.put("success", false);
				modelMap.put("errMsg", e.toString());
			}
	    	//关键操作，需要记录
	    	if ((boolean) modelMap.get("success")) {
			    this.markOperation(request, "新增保单信息", policy.toString(), "操作成功", null);
	    	} else {
			    this.markOperation(request, "新增保单信息", policy.toString(), (String)modelMap.get("errMsg"), null);
	    	}
		} else {
			modelMap.put("success", false);
			modelMap.put("errMsg", "出现异常，执行出错！\n请检查投保单号是否已经存在。");
		}
		return modelMap;
	}
	
	@RequestMapping(value = "/modifyPolicy", method={RequestMethod.POST})
	@ResponseBody
	private Map<String, Object> modifyPolicy(@RequestBody Policy policy, HttpServletRequest request) {
		Map<String, Object> modelMap = new HashMap<String, Object>();
		if (null == policy) {
			modelMap.put("success", false);
			modelMap.put("errMsg", "Empty Policy Entity!");
			return modelMap;
		}
		//更新保单的状态信息
		policy.setStatusInfo(PolicyStatusEnum.stateOf(policy.getStatus()).getStateInfo());
	    PolicyExecution exe = policyService.modifyPolicy(policy);
		if (null != exe ) {
			try {
				modelMap.put("total",exe.getCount());
				modelMap.put("rows",exe.getList());
				modelMap.put("success", true);
			} catch (Exception e) {
				modelMap.put("success", false);
				modelMap.put("errMsg", e.toString());
			}
	    	//关键操作，需要记录
	    	if ((boolean) modelMap.get("success")) {
			    this.markOperation(request, "修改保单信息", policy.toString(), "操作成功", null);
	    	} else {
			    this.markOperation(request, "修改保单信息", policy.toString(), (String)modelMap.get("errMsg"), null);
	    	}
		} else {
			modelMap.put("success", false);
			modelMap.put("errMsg", "Empty List");
		}
		return modelMap;
	}
	
	@RequestMapping(value = "/removePolicy", method={RequestMethod.POST})
	@ResponseBody
	private Map<String, Object> removePolicy(HttpServletRequest request) {
		Map<String, Object> modelMap = new HashMap<String, Object>();
		String insureNoString = HttpServletRequestUtil.getString(request, "insureNos");
		List<Policy> list = new ArrayList<Policy>();
		Policy policy ;
	    if (!"".equals(insureNoString) && insureNoString!=null) {
	    	String[] insureNos = insureNoString.split(",");
	    	for (int i=0; i<insureNos.length; i++) {
	    		policy = new Policy();
	    		policy.setInsureNo(insureNos[i]);
	    		list.add(policy);
	    	}
	    	PolicyExecution exe = policyService.batchRemovePolicy(list);
	    	if (null != exe ) {
				try {
					modelMap.put("total",exe.getCount());
					modelMap.put("success", true);
				} catch (Exception e) {
					modelMap.put("success", false);
					modelMap.put("errMsg", e.toString());
				}
		    	//关键操作，需要记录
		    	if ((boolean) modelMap.get("success")) {
				    this.markOperation(request, "删除保单信息", insureNoString, "操作成功", null);
		    	} else {
				    this.markOperation(request, "删除保单信息", insureNoString, (String)modelMap.get("errMsg"), null);
		    	}
			} else {
				modelMap.put("success", false);
				modelMap.put("errMsg", "Empty List");
			}
	    } else {
			modelMap.put("success", false);
			modelMap.put("errMsg", "Empty Parameter");
		}
		return modelMap;
	}	
	
	
	/**
	 * 这个方法用于将保单寄出
	 * @param request,insure_no
	 * @return
	 */
	@RequestMapping(value = "/sentoutPolicy", method={RequestMethod.GET,RequestMethod.POST})
	@ResponseBody
	private Map<String, Object> sentoutPolicy(HttpServletRequest request) {
		Map<String, Object> modelMap = new HashMap<String, Object>();
		PolicyExecution policyExe = null;
		DeliverInfoExecution deliverInfoExe = null;
	    String insureNo = HttpServletRequestUtil.getString(request, "insure_no");
	    if (!"".equals(insureNo) && insureNo!=null) {
	    	Policy policy = policyService.getPolicy(insureNo);
	    	DeliverInfo deliverInfo = new DeliverInfo();
	    	if (policy!=null) {
	    		//判断这个保单今天是否有寄出记录
	    		deliverInfo.setInsureNo(policy.getInsureNo());
	    		deliverInfo.setDeliverTime(new Date());
	    		deliverInfoExe = deliverInfoService.getDeliverInfoList(deliverInfo,0,100);
	    		if (deliverInfoExe.getCount()>0) {
	    			//如果配送信息中已经存在这张保单今天的寄出信息，直接返回失败信息，不予插入。
	    			modelMap.put("success", false);
	    			modelMap.put("errTab", "stop");
	    			modelMap.put("errMsg", "该保单在今日已存在寄出信息！本次操作失败！");
	    	    	return modelMap;
	    		}
	    		//判断这个保单是否有警告及中断信息
	    		PolicyMonitor policyMonitor = policyMonitorService.getPolicyMonitor(insureNo);
	    		if (policyMonitor!=null) {
    				//如果存在中断信息，且中断标签为2001，要求中断寄出的，则直接返回暂停，不予插入。
	    			if ( policyMonitor.getHoldFlag()!=null
	    				&& policyMonitor.getHoldFlag()==PolicyMonitorEnum.HALT_SEND.getState()) {
		    			modelMap.put("success", false);
		    			modelMap.put("errTab", "stop");
		    			modelMap.put("errMsg", "【中断保单寄出操作】"+policyMonitor.getHoldInfo());
		    	    	return modelMap;	    				
	    			}
		    		//判断这个保单是否有警告信息,如果有，则将信息添加到map中，然后继续执行程序
	    			if ( policyMonitor.getWarnFlag()!=null 
	    				&& policyMonitor.getWarnFlag()==PolicyMonitorEnum.WARN_REPEAT.getState()) {
		    			modelMap.put("warningTab", PolicyMonitorEnum.WARN_REPEAT.getState());
		    			modelMap.put("warningMsg", policyMonitor.getWarnInfo());
	    			}
	    		}	    		
	    		policy.setStatus(Integer.valueOf(PolicyStatusEnum.SEND.getState()));
	    		policy.setStatusInfo(PolicyStatusEnum.SEND.getStateInfo());
	    		if (policy.getDeliverCount()==null) {
	    			policy.setDeliverCount(1);
	    		} else {
	    			policy.setDeliverCount(policy.getDeliverCount()+1);
	    		} 
	    		deliverInfo.setDeliverTimes(policy.getDeliverCount());
	    		deliverInfo.setAddress(policy.getAddress());
	    		deliverInfo.setRecipient(policy.getApplicant());
	    		deliverInfo.setTelephone(policy.getMobilephone());	    		
	    		policyExe = policyService.modifyPolicy(policy); 
	    		deliverInfoExe = deliverInfoService.addDeliverInfo(deliverInfo);
	    		if (null != policyExe && null != deliverInfoExe) {
	    			try {
	    				modelMap.put("data",policyExe.getPolicy());
	    				modelMap.put("success", true);
	    			} catch (Exception e) {
	    				modelMap.put("success", false);
	    				modelMap.put("errMsg", e.toString());
	    			}
	    		} else {
	    			modelMap.put("success", false);
	    			modelMap.put("errMsg", "Empty List");
	    		}
		    	//关键操作，需要记录
		    	if ((boolean) modelMap.get("success")) {
				    this.markOperation(request, "保单寄出", insureNo+":"+deliverInfo.toString(), "操作成功", null);
		    	} else {
				    this.markOperation(request, "保单寄出", insureNo+":"+deliverInfo.toString(), (String)modelMap.get("errMsg"), null);
		    	}
	    	} else {
				modelMap.put("success", false);
				modelMap.put("errMsg", "Empty insure information");
	    	}
	    } else {
			modelMap.put("success", false);
			modelMap.put("errMsg", "Empty insure number");
	    }	
		return modelMap;
	}	
	
	
	/**
	 * 这个方法用于保单回销登记
	 * 记录保单的回销时间，以及修改保单的状态为已回销
	 * @param request,insure_no
	 * @return
	 */
	@RequestMapping(value = "/markReceipt", method={RequestMethod.GET,RequestMethod.POST})
	@ResponseBody
	private Map<String, Object> markReceipt(HttpServletRequest request) {
		Map<String, Object> modelMap = new HashMap<String, Object>();
		PolicyExecution policyExe = null;
	    String insureNo = HttpServletRequestUtil.getString(request, "insure_no");
	    if (!"".equals(insureNo) && insureNo!=null) {
	    	Policy policy = policyService.getPolicy(insureNo);
	    	if (policy!=null) {
	    		//判断这个保单是否有回销记录
	    		if (policy.getStatus()==PolicyStatusEnum.RECEIPT.getState() || policy.getReceiptTime()!=null) {
	    			modelMap.put("success", false);
	    			modelMap.put("errMsg", "Data existed");
	    	    	return modelMap;
	    		}
	    		//判断这个保单是否有中断信息
	    		PolicyMonitor policyMonitor = policyMonitorService.getPolicyMonitor(insureNo);
	    		if (policyMonitor!=null) {
    				//如果存在中断信息，且中断标签为2002，要求中断回销的，则直接返回暂停，不予插入。
	    			if ( policyMonitor.getHoldFlag()!=null
	    				&& policyMonitor.getHoldFlag()==PolicyMonitorEnum.HALT_RECEIPT.getState()) {
		    			modelMap.put("success", false);
		    			modelMap.put("errTab", "stop");
		    			modelMap.put("errMsg", "【中断保单回销操作】"+policyMonitor.getHoldInfo());
		    	    	return modelMap;	    				
	    			}
		    		//判断这个保单是否有警告信息,如果有，则将信息添加到map中，然后继续执行程序
	    			if ( policyMonitor.getWarnFlag()!=null 
	    				&& policyMonitor.getWarnFlag()!=PolicyMonitorEnum.NORMAL.getState()) {
		    			modelMap.put("warningTab", policyMonitor.getWarnFlag());
		    			modelMap.put("warningMsg", policyMonitor.getWarnInfo());
	    			}
	    		}	    
	    		policy.setStatus(PolicyStatusEnum.RECEIPT.getState());
	    		policy.setStatusInfo(PolicyStatusEnum.RECEIPT.getStateInfo());
	    		policy.setReceiptTime(new Date());	    		   		
	    		policyExe = policyService.modifyPolicy(policy); 
	    		if (null != policyExe) {
	    			try {
	    				modelMap.put("data",policyExe.getPolicy());
	    				modelMap.put("success", true);
	    			} catch (Exception e) {
	    				modelMap.put("success", false);
	    				modelMap.put("errMsg", e.toString());
	    			}
	    		} else {
	    			modelMap.put("success", false);
	    			modelMap.put("errMsg", "Empty List");
	    		}
	    	} else {
				modelMap.put("success", false);
				modelMap.put("errMsg", "Empty insure information");
	    	}   
	    	//更新保单配送信息，取出最新一条配送记录
	    	DeliverInfo deliverLastInfo  = deliverInfoService.getDeliverLastInfo(insureNo); 	
	    	if (deliverLastInfo!=null) {
	    		deliverLastInfo.setReturnTime(policy.getReceiptTime());
	    		DeliverInfoExecution deliverInfoExe = null;	   		
	    		deliverInfoExe = deliverInfoService.modifyDeliverInfo(deliverLastInfo); 
	    		if (null == deliverInfoExe) {
	    			modelMap.put("success", false);
	    			modelMap.put("errMsg", "Error in modify DeliverInfo");
	    		}
	    	} else {
				modelMap.put("success", false);
				modelMap.put("errMsg", "Empty insure deliver information");
	    	}
	    	//关键操作，需要记录
	    	if ((boolean) modelMap.get("success")) {
			    this.markOperation(request, "保单回销", policy.toString(), "操作成功", null);
	    	} else {
			    this.markOperation(request, "保单回销", policy.toString(), (String)modelMap.get("errMsg"), null);
	    	}
	    } else {
			modelMap.put("success", false);
			modelMap.put("errMsg", "Empty insure number");
	    }	
		return modelMap;
	}	
	
	/**
	 * 这个方法用于保单回退登记（所有资料退回来）
	 * 记录保单的回退时间，以及修改保单的状态为已回退
	 * @param request,insure_no
	 * @return
	 */
	@RequestMapping(value = "/markReturn", method={RequestMethod.GET,RequestMethod.POST})
	@ResponseBody
	private Map<String, Object> markReturn(HttpServletRequest request) {
		Map<String, Object> modelMap = new HashMap<String, Object>();
	    String insureNo = HttpServletRequestUtil.getString(request, "insure_no");
	    if (!"".equals(insureNo) && insureNo!=null) {
	    	//更新保单信息
	    	Policy policy = policyService.getPolicy(insureNo);	  
	    	if (policy!=null) {
	    		//判断这个保单是否有中断信息
	    		PolicyMonitor policyMonitor = policyMonitorService.getPolicyMonitor(insureNo);
	    		if (policyMonitor!=null) {
    				//如果存在中断信息，且中断标签为2003，要求中断回退的，则直接返回暂停，不予插入。
	    			if (policyMonitor.getHoldFlag()!=null
		    			&& policyMonitor.getHoldFlag()==PolicyMonitorEnum.HALT_RETURN.getState()) {
		    			modelMap.put("success", false);
		    			modelMap.put("errTab", "stop");
		    			modelMap.put("errMsg", "【中断保单回退操作】"+policyMonitor.getHoldInfo());
		    	    	return modelMap;	    				
	    			}
		    		//判断这个保单是否有警告信息,如果有，则将信息添加到map中，然后继续执行程序
	    			if (null!=policyMonitor.getWarnFlag()
		    			&& policyMonitor.getWarnFlag()!=PolicyMonitorEnum.NORMAL.getState()) {
		    			modelMap.put("warningTab", policyMonitor.getWarnFlag());
		    			modelMap.put("warningMsg", policyMonitor.getWarnInfo());
	    			}
	    		}	    
	    		policy.setStatus(PolicyStatusEnum.BACKALL.getState());
	    		policy.setStatusInfo(PolicyStatusEnum.BACKALL.getStateInfo());
	    		policy.setReturnTime(new Date());	    	
				PolicyExecution policyExe = null;	   		
	    		policyExe = policyService.modifyPolicy(policy); 
	    		if (null != policyExe) {
	    			try {
	    				modelMap.put("data",policyExe.getPolicy());
	    				modelMap.put("success", true);
	    			} catch (Exception e) {
	    				modelMap.put("success", false);
	    				modelMap.put("errMsg", e.toString());
	    			}
	    		} else {
	    			modelMap.put("success", false);
	    			modelMap.put("errMsg", "Empty List");
	    		}
	    	} else {
				modelMap.put("success", false);
				modelMap.put("errMsg", "Empty insure information");
	    	}	   
	    	//更新保单配送信息，取出最新一条配送记录
	    	DeliverInfo deliverLastInfo  = deliverInfoService.getDeliverLastInfo(insureNo); 	
	    	if (deliverLastInfo!=null) {
	    		deliverLastInfo.setReturnNo("00000000");
	    		deliverLastInfo.setReturnTime(policy.getReturnTime());
	    		DeliverInfoExecution deliverInfoExe = null;	   		
	    		deliverInfoExe = deliverInfoService.modifyDeliverInfo(deliverLastInfo); 
	    		if (null == deliverInfoExe) {
	    			modelMap.put("success", false);
	    			modelMap.put("errMsg", "Error in modify DeliverInfo");
	    		}
	    	} else {
				modelMap.put("success", false);
				modelMap.put("errMsg", "Empty insure deliver information");
	    	}
	    	//关键操作，需要记录
	    	if ((boolean) modelMap.get("success")) {
			    this.markOperation(request, "保单退回", policy.toString(), "操作成功", null);
	    	} else {
			    this.markOperation(request, "保单退回", policy.toString(), (String)modelMap.get("errMsg"), null);
	    	}
	    } else {
			modelMap.put("success", false);
			modelMap.put("errMsg", "Empty insure number");
	    }	
		return modelMap;
	}
	
	private Boolean markOperation(HttpServletRequest request, 
						String target, 
						String operation, 
						String result, 
						String remark) {
			MDMISOperationTrace operationTrace = new MDMISOperationTrace();
			//从session中获取用户信息
			LocalUser localUser = (LocalUser) request.getSession().getAttribute("login_user");
			// 如果没有登陆用户的信息，直接返回失败。
			if (null==localUser) return false;
			operationTrace.setUserID(localUser.getUserID());
			operationTrace.setUsername(localUser.getUsername());
			operationTrace.setNameCN(localUser.getNameCN());
			//从session中获取当前角色信息
			Role loginRole = (Role) request.getSession().getAttribute("login_role");
			// 如果没有登陆角色的信息，创建一个空角色。
			if (null==loginRole) loginRole = new Role();
			operationTrace.setRoleID(loginRole.getRoleID());
			operationTrace.setRoleName(loginRole.getRoleName());
			//从request中获取 当前操作的IP地址    
			operationTrace.setSource(HttpServletRequestUtil.getIP(request));
			//其它参数赋值
			operationTrace.setActionTime(new Date());
			operationTrace.setTarget(target);
			operationTrace.setOperation(operation);
			operationTrace.setResult(result);
			operationTrace.setRemark(remark);
			MDMISOperationTraceExecution exe = operationTraceService.addOperationTrace(operationTrace);
			if (null != exe ) {
				return true;
			} else {
				return false;
		}		
	}
}
